package cn.vc.auth.service;

import cn.vc.auth.util.EmailUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <h1>验证码服务</h1>
 */
@Service
public class CaptchaService {
    Random random = new Random();
    /**
     * 前缀:Captcha_；过期时间:2；时间单位:分；储存位置:本地；
     */
    @CreateCache(name = "Captcha_", expire = 2, timeUnit = TimeUnit.MINUTES, cacheType = CacheType.LOCAL)
    private Cache<String, String> jetCache;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    EmailUtil emailUtil;
    //发送人
    String from = "vq202306@163.com(VQ官方邮箱)";
    //标题
    String subject = "红珊瑚邮箱验证码";

    public enum prefixType {
        signIn("signIn"),//注册
        deleteUser("deleteUser"),//注销用户
        forgot("forgot"),//忘记密码
        updateUser("updateUser");//修改用户
        private final String value;
        prefixType(String value) {
            this.value = value;
        }
        public String getValue() {
            return this.value;
        }
    }

    /**
     * 获取随机验证码
     * @return
     */
    private String getCaptcha() {
        StringBuilder str = new StringBuilder();
        //生成随机六位0到9的数字
        for (int i = 0; i < 6; i++) {
            str.append(String.valueOf(random.nextInt(10)));
        }
        return str.toString();
    }
    /**
     * <h2>生成并发送验证码</h2>
     * @param email 电子邮箱
     * @return
     */
    public String sendCaptcha(String email, String prefix) throws MessagingException {
        //判断电子邮箱是否符合格式
        if (!"com".equals(email.substring(email.length()-3))) return null;
        //获取随机验证码
        String code = getCaptcha();
        //生成消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject(subject);
        message.setText("您的邮箱验证码为：<div style='font-size: 50px'>"+code+"</div>该验证码 2 分钟内有效。为了保障您的账户安全，请勿向他人泄漏验证码信息。");
        //发送消息
        emailUtil.send(message, true);
        //向缓存添加
        jetCache.put(prefix+"_"+email, code);
        return code;
    }
    /**
     * 判断该验证码是否正确
     * @param prefix_email 电子邮箱
     * @param captcha 验证码
     * @return
     */
    public boolean comparisonCaptcha(String prefix_email, String captcha) {
        if (captcha==null) return false;
        return captcha.equals(jetCache.get(prefix_email));
    }
}
